package com.fmi.timedealer.notifications;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;
import com.fmi.timedealer.plan.Plan;
import com.fmi.timedealer.plan.PlanPlannedActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class NotificationReceiver extends BroadcastReceiver {
	
	public static final int NOTIFICATION_ID = 1;
	public static final String NOTIFICATION_EXTRA_KEY = "NotificationKey";
	public static final String NOTIFICATION_EXTRA_ACTIVITIES_KEY = "NotificationPlansKey";
	public static final String BROADCAST_ACTION = "com.fmi.timedealer.NOTIFICATION";
	
	private static final String PREFS_NAME = "NotificationPrefsFile";
	private static final String PREFS_DAY_KEY = "DayOfYear";
	
	private IDataManager dbManager = null;
	private ArrayList<Integer> planIds;

	@Override
	public void onReceive(Context context, Intent intent) {
		
		SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
		int dayOfYear = settings.getInt(PREFS_DAY_KEY, 0);
		if (dayOfYear != Calendar.getInstance().get(Calendar.DAY_OF_YEAR)) {
			checkProgress(context, intent);
		}
	}
	
	private void checkProgress(Context context, Intent intent) {
		
		dbManager = new SQLiteDataManager("MyDB", context);
		planIds = new ArrayList<Integer>();
		
		Date now = new Date();
		Date planMiddle;
		long start;
		long end;
		long diff;
		boolean hasAnyPlan = false;
		
		ArrayList<Plan> plans = dbManager.getPlans();
		for (Plan p : plans) {

			start = p.getStart().getTime();
			end = p.getEnd().getTime();
			
			diff = (end - start) / 2;
			planMiddle = new Date(start + diff);
			
			if (now.after(planMiddle)) {
				planIds.add(p.getId());
				hasAnyPlan = true;
			}
		}
		
		if (hasAnyPlan) {
			createNotification(context, intent);
		}
	}
	
	private void createNotification(Context context, Intent intent) {
		
		int icon = android.R.drawable.stat_notify_sync;        		// icon from resources
		CharSequence tickerText = "Time Dealer plan progress";      // ticker-text
		long when = System.currentTimeMillis();         			// notification time
		
		CharSequence contentTitle = "Plans progress";				// message title
		CharSequence contentText = "View planned activities progress";      						// message text

		Intent notificationIntent = new Intent(context, PlanPlannedActivity.class);
		StringBuilder sb = new StringBuilder();

		for (Integer obj : planIds) {
		  sb.append(obj.toString());
		  sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		
		notificationIntent.putExtra(NOTIFICATION_EXTRA_ACTIVITIES_KEY, sb.toString());
		notificationIntent.putExtra(NOTIFICATION_EXTRA_KEY, true);
		
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

		// the next two lines initialize the Notification, using the configurations above
		Notification notification = new Notification(icon, tickerText, when);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		
		// Add sound
		notification.defaults |= Notification.DEFAULT_SOUND;
		
		// Add flashing light
		notification.defaults |= Notification.DEFAULT_LIGHTS;
		
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(ns);
		mNotificationManager.notify(NOTIFICATION_ID, notification);
		
		// Indicate for notification in local store
		SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(PREFS_DAY_KEY, Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
		editor.commit();
	}
}
